<?php

namespace Tasker\Components\Forms;

use \Nette\Application\UI\Control,
	\Nette\Application\UI\Form;

/**
 * Description of ProjectForm
 * @property-read BasePresenter $presenter
 * @author Jan Voracek
 */
class ProjectForm extends Control
{

	private $parentProject;
	private $id;
	private $redirect;

	public function __construct($parentProject = NULL)
	{
		$this->parentProject = $parentProject;
	}

	public function setRedirect($redirect)
	{
		$this->redirect = $redirect;
	}


	public function render($id=null)
	{
		$dir = dirname($this->reflection->fileName);
		$this->template->setFile($dir . '/projectForm.latte');

		$this->id = $id;



		if (count($this['editForm']['project_id']->getItems()) == 0)
		{
			$this->template->canCreateProject = false;
		} else
		{
			$this->template->canCreateProject = true;
			
			if ($id != null)
			{
				$projectModel = $this->presenter->context->models->project->find($id);
				$project = $projectModel->getProject();
				$projectMembers = array();
				foreach ($projectModel->getProjectTeam() as $projectMember)
				{
					$projectMembers[$projectMember['user_id']] = array(
						'member' => $projectMember['user_id'],
						'role' => $projectMember['project_role_id']
					);
				}
				$project['members'] = $projectMembers;
				$project['id'] = $id;
				if ($this->parentProject != null)
				{
					$project['project_id'] = $this->parentProject;
				}
				$project_task_types = array();
				foreach($projectModel->getTaskTypes() as $taskType){
					$project_task_types[] = $taskType['task_type_id'];
				}
				$project['task_types'] = $project_task_types;
				
				$this['editForm']->setDefaults($project);
				$this->template->edit = true;
			}

			$usersModel = $this->presenter->context->models->users;
			
			$departments = $usersModel->getDepartments();
			$skills = $usersModel->getSkills();

			$usersWithSkill = array();
			foreach($skills as $skill){
				$usersWithSkill[$skill['id']] = array();
			}
			foreach ($usersModel->getUsersSkills() as $userSkill)
			{
				$usersWithSkill[$userSkill['skill_id']][] = $userSkill['user_id'];
			}
			
			$usersInDepartment = array();
			$skillsInDepartment = array();
			
			foreach($departments as $department){
				$usersInDepartment[$department['id']] = array();
				$skillsInDepartment[$department['id']] = array();
			}
			
			foreach($usersModel->getUsers() as $user){
				$usersInDepartment[$user['department_id']][] = $user['id'];
			}
			
			foreach($usersModel->getSkills() as $skill){
				$skillsInDepartment[$skill['department_id']][] = $skill['id'];
			}
			$this->template->usersWithSkill = $usersWithSkill;
			$this->template->usersInDepartment = $usersInDepartment;
			$this->template->skillsInDepartment = $skillsInDepartment;
			$this->template->skills = $skills;
			$this->template->departments = $departments;
		}

		$this->template->render();
	}

	protected function createComponentEditForm($name)
	{
		$form = new Form($this, $name);
		$form->addGroup();

		$form->addText('name', 'Název:')
				->setRequired('Název projektu je povinný, vyplňte ho, prosím.');
		$form->addDatePicker('deadline', 'Deadline:');

		$form->addRadioList('public', 'Veřejný:', array('yes' => 'Ano', 'no' => 'Ne'))
				->setDefaultValue('yes')
				->setRequired('Vyberte, prosím, zda je úkol veřejný či nikoliv.')
				->getSeparatorPrototype()->setName('span');


		$for = ($this->id === null ? 'add' : 'edit');
		$form->addSelect('project_id', 'Podprojektem:', $this->getAllowedProjects($for));

		$form->addTextArea('description', 'Popis:');

		$usersModel = $this->presenter->context->models->users;
		$tasksModel = $this->presenter->context->models->tasks;
		$projectsModel = $this->presenter->context->models->projects;
		$taskContextModel = $this->presenter->context->models->taskContext;
		
		$taskTypes = array();
		foreach($taskContextModel->getTypes() as $type)
		{
			$taskTypes[$type['id']] = $type['name'];
		}
		
		$form->addCheckboxList('task_types','Typy úkolů:',$taskTypes);
		
		$form->addRadioList('closed', 'Stav projektu:', array('no'=>'Otevřený','yes'=>'Uzavřený'));
		
		$users = array();
		$roles = array();
		foreach ($usersModel->getUsers() as $user)
		{
			$taskCount = $tasksModel->getTasksCount($user['id']);
			$users[$user['id']] = $user['name'] . " " . $user['surname'] . " (" . $taskCount . ")";
		}
		foreach ($projectsModel->getRoles() as $role)
		{
			$roles[$role['id']] = $role['name'];
		}


		$form->addCheckboxDetailList('members', 'Členové týmu:', $users, $roles);


		$form->addHidden('id');

		$form->addSubmit('send', 'Uložit');

		$form->onSuccess[] = callback($this, 'projectFormSubmitted');
		return $form;
	}

	public function projectFormSubmitted(Form $form)
	{
		$values = $form->getValues();
		$id = $values['id'];
		if ($id != '')
		{ // Project is edited
			$projectModel = $this->presenter->context->models->project->find($id);
			$projectModel->save($values);
		} else
		{ // New project
			$projectModel = $this->presenter->context->models->project->createNewProject($values);
			$id = $projectModel->getId();
		}
		$this->getPresenter()->flashMessage('Projekt byl uložen');
		if($this->redirect !== null){
			$this->getPresenter()->redirectUrl($this->redirect);
		}else{
			$this->getPresenter()->redirect('Project:overview', $id);
		}
	}

	private function getAllowedProjects($for = 'add')
	{
		$projects = $this->presenter->context->models->projects;
		$allowedProjects = array();
		if ($this->getPresenter()->getUser()->isAllowed('project', $for))
		{
			$allowedProjects[0] = "Žádného projektu";
		}
		foreach ($projects->getAllProjects() as $project)
		{
			$resource = new \Tasker\Authorization\ProjectResource($project['id']);

			if ($this->getPresenter()->getUser()->isAllowed('project', $for) || $this->getPresenter()->getUser()->isAllowed($resource, 'project_'.$for))
			{
				$allowedProjects[$project['id']] = $project['name'];
			}
		}
		return $allowedProjects;
	}

}
